package com.glory.huaweipda.view

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.view.View.GONE
import android.widget.*
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.glory.huaweipda.R
import com.glory.huaweipda.adapter.DialogAdapter
import com.glory.huaweipda.base.Constant
import com.glory.huaweipda.base.MyApp
import com.glory.huaweipda.bean.DialogLotBean
import com.glory.huaweipda.bean.LotInfoBean
import com.glory.huaweipda.viewmodel.SkipDialogModel
import com.glory.mvvmnet.base.BaseActivity
import com.glorysoft.hlgdpda.utils.PopWindowsUtils
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_SharePreferencesUtils
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers
import kotlinx.android.synthetic.main.activity_scan_start.*
import kotlinx.android.synthetic.main.activity_system_set.*
import java.util.*
import kotlin.collections.ArrayList


/**
 * FileName: SkipDialogActivity
 * Author: XJH
 * Date: 2021/7/22 17:13
 * Description:
 * History:
 */
class SkipDialogActivity : BaseActivity<SkipDialogModel>() {
    private var skipDialog: FreeUI_GeneralFragmentDialog? = null
    private var codePop: PopWindowsUtils.GeneralPop? = null
    var type: String = ""
    var handler: Handler = object : Handler() {
        @SuppressLint("HandlerLeak")
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                0x10 -> {
                    var s: String = msg.obj as String
                    type = "oo"
                    val intent = Intent()
                    intent.putExtra("showPlugin", "errorLog")
                    intent.putExtra("error", s)
                    val clazz = Class.forName("com.glory.huaweipda.view.SkipDialogActivity")
                    intent.setClass(this@SkipDialogActivity, clazz)
                    startActivity(intent)
                }
                0x20 -> {
                    var s: String = msg.obj as String
                    val intent = Intent()
                    intent.putExtra("showPlugin", "tips")
                    intent.putExtra("tips", s)
                    val clazz = Class.forName("com.glory.huaweipda.view.SkipDialogActivity")
                    intent.setClass(this@SkipDialogActivity, clazz)
                    startActivity(intent)
                }
                0x30 -> {
                    var s: String = msg.obj as String
                    val intent = Intent()
                    intent.putExtra("showPlugin", "arrival")
                    intent.putExtra("track", s)
                    val clazz = Class.forName("com.glory.huaweipda.view.SkipDialogActivity")
                    intent.setClass(this@SkipDialogActivity, clazz)
                    startActivity(intent)
                }
            }
        }
    }


    private fun initView() {
        val extra = intent.getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY)

        when {
            extra!!.contains("Scan_Start") -> {
                val customDialog = getCustomDialog(true, object : OnConfirmListener {
                    override fun onConfirm(eqpID: String, user: String, lotID: String,dialog:MaterialDialog) {
                        val intent = Intent()
                        viewModel.defaultLotInfo(eqpID, user, lotID)
                        viewModel.defUI.callObserve.observe(this@SkipDialogActivity) {
                            if (type.equals("oo")) it.type = -1
                            when (it.type) {
                                0 -> {
                                    val lotsBean = it.item as LotInfoBean
                                    val clazz =
                                        Class.forName("com.glory.huaweipda.view.TrackInActivity")
                                    val bundle = Bundle()
                                    bundle.putString("eqpID",eqpID)
                                    bundle.putString("user",user)
                                    bundle.putString("lotID",lotID)
                                    bundle.putSerializable("lotsBean",lotsBean)
                                    intent.putExtras(bundle)
                                    intent.setClass(this@SkipDialogActivity, clazz)
                                    startActivity(intent)
//                                    dialog.dismiss()
                                    finish()
                                }
                                1 -> {
                                    val lotsBean = it.item as LotInfoBean
                                    val clazz =
                                        Class.forName("com.glory.huaweipda.view.TrackOutActivity")
                                    intent.setClass(this@SkipDialogActivity, clazz)

                                    val bundle = Bundle()
                                    bundle.putString("eqpID",eqpID)
                                    bundle.putString("user",user)
                                    bundle.putString("lotID",lotID)
                                    bundle.putSerializable("lotsBean",lotsBean)
                                    intent.putExtras(bundle)
                                    startActivity(intent)
//                                    dialog.dismiss()
                                    finish()
                                }
                                2 -> {

                                }
                            }
                        }


                    }

                })
                customDialog.show()
            }
            extra.contains("mState") -> {
                val trackOutDialog = getAddressDialog("mstate", object : OnAddressDialog {
                    override fun onAddress(address: String,isState:Boolean) {
                        viewModel.defaultEqpStateChangeInfo(address,isState)
                    }
                })
                trackOutDialog.show()
            }

//            extra.contains("Scan_End") -> {
//                val customDialog = getCustomDialog(true, object : OnConfirmListener {
//                    override fun onConfirm(eqpID: String, user: String, lotID: String) {
//                        val intent = Intent()
//                        val clazz = Class.forName("com.glory.huaweipda.view.TrackOutActivity")
//                        intent.putExtra("eqpID", eqpID)
//                        intent.putExtra("user", user)
//                        intent.putExtra("lotID", lotID)
//                        intent.setClass(this@SkipDialogActivity, clazz)
//                        startActivity(intent)
//                        finish()
//                    }
//
//                })
//                customDialog.show()
//            }

            extra.contains("system_set_bot") -> {
                val trackOutDialog = getTrackOutDialog("system_set_bot", object : OnSystemSetBot {
                    override fun onSystemSetBot(serverAddress: String) {

                    }
                })
                trackOutDialog.show()
            }

            extra.contains("server_address") -> {
                val trackOutDialog = getAddressDialog("server_address", object : OnAddressDialog {
                    override fun onAddress(address: String,isState:Boolean) {
                        if(isState){
                            val intent = Intent()
                            intent.putExtra("server_address", address)
                            setResult(1, intent)
                        }
                    }
                })
                trackOutDialog.show()
            }

            extra.contains("file_address") -> {
                val trackOutDialog = getAddressDialog("file_address", object : OnAddressDialog {
                    override fun onAddress(address: String,isState:Boolean) {
                        if(isState) {
                            val intent = Intent()
                            intent.putExtra("file_address", address)
                            setResult(2, intent)
                        }
                    }
                })
                trackOutDialog.show()
            }

            extra.contains("connectTimeout") -> {
                val trackOutDialog = getAddressDialog("connectTimeout", object : OnAddressDialog {
                    override fun onAddress(address: String,isState:Boolean) {
                        if(isState) {
                            val intent = Intent()
                            intent.putExtra("connectTimeout", address)
                            setResult(4, intent)
                        }
                    }
                })
                trackOutDialog.show()
            }

            extra.contains("region_selection") -> {
                val trackOutDialog = getRegionSelectionDialog(object : OnRegionSelectionDialog {
                    override fun onRegionSelection(selection: String) {
                        val intent = Intent()
                        intent.putExtra("region_selection", selection)
                        setResult(3, intent)
                    }
                })
                trackOutDialog.show()
            }

            extra.contains("arrival") -> {
                val trackOutDialog = getTrackOutDialog("arrival", object : OnSystemSetBot {
                    override fun onSystemSetBot(serverAddress: String) {

                    }
                })
                trackOutDialog.show()
            }

            extra.contains("tips") -> {
                val trackOutDialog = getTrackOutDialog("tips", object : OnSystemSetBot {
                    override fun onSystemSetBot(serverAddress: String) {

                    }
                })
                trackOutDialog.show()
            }

            extra.contains("errorLog") -> {
                val trackOutDialog = getTrackOutDialog("errorLog", object : OnSystemSetBot {
                    override fun onSystemSetBot(serverAddress: String) {

                    }
                })
                trackOutDialog.show()
            }

            extra.contains("set_number") -> {
                val trackOutDialog = getTrackOutDialog("set_number", object : OnSystemSetBot {
                    override fun onSystemSetBot(serverAddress: String) {

                    }
                })
                trackOutDialog.show()
            }

            extra.contains("again") -> {
                val trackOutDialog = getDescDialog(object : OnAddressDialog {
                    override fun onAddress(address: String,isState:Boolean) {
                        if(isState) {
                            val intent = Intent()
                            intent.putExtra("again", address)
                            setResult(1, intent)
                        }
                    }
                })
                trackOutDialog.show()
            }
        }
    }

    private fun getRegionSelectionDialog(selection: OnRegionSelectionDialog): MaterialDialog {
        val dialog = MaterialDialog(this)
            .cancelable(false)
            .cornerRadius(12f)
            .customView(R.layout.dialog_region_selection, noVerticalPadding = true)
            .lifecycleOwner(this)
        val contentView = dialog.getCustomView()
        val flType: FrameLayout = contentView.findViewById(R.id.flType)
        val ivTypeArrow: ImageView = contentView.findViewById(R.id.ivTypeArrow)
        val flPositionList: LinearLayout = contentView.findViewById(R.id.flPositionList)
        val ivClose: ImageView = contentView.findViewById(R.id.ivClose)
        val region_text: TextView = contentView.findViewById(R.id.tvType)
        val region_no: TextView = contentView.findViewById(R.id.region_no)
        val region_yes: TextView = contentView.findViewById(R.id.region_yes)

        val areaArrayList = intent.getStringArrayListExtra("areaList")

        val list: ArrayList<String> = ArrayList()
        if (areaArrayList != null) {
            list.addAll(areaArrayList)
        }
        val area = FreeApi_SharePreferencesUtils.getSharePre(
            "SystemSet",
            "area",
            applicationContext
        )
        region_text.text = area

        flPositionList.setOnClickListener {
            if (codePop == null) {
                codePop = PopWindowsUtils.getOneChoosePop(this, flType.width, list,
                    ivTypeArrow, object : PopWindowsUtils.PopTextAndPositionCallback {
                        override fun onSuccess(string: String, potion: Int) {
                            region_text.setText(string)
                        }
                    })
            }

            if (codePop!!.isShowing) {
                codePop?.dismiss()
            } else {
                PopWindowsUtils.setArrowShow(ivTypeArrow)
                codePop?.showAsDropDown(flType, 0, 0)
            }
        }

        ivClose.setOnClickListener {
            dialog.dismiss()
            finish()
        }
        region_no.setOnClickListener {
            dialog.dismiss()
            finish()
        }
        region_yes.setOnClickListener {
            selection.onRegionSelection(region_text.text.toString())
            dialog.dismiss()
            finish()
        }

        return dialog
    }

    private fun getAddressDialog(ress: String, address: OnAddressDialog): MaterialDialog {
        val dialog = MaterialDialog(this)
            .cancelable(false)
            .cornerRadius(12f)
            .customView(R.layout.dialog_server_address, noVerticalPadding = true)
            .lifecycleOwner(this)
        val contentView = dialog.getCustomView()

        val ivClose: ImageView = contentView.findViewById(R.id.ivClose)
        val add_no: TextView = contentView.findViewById(R.id.add_no)
        val add_yes: TextView = contentView.findViewById(R.id.add_yes)
        val add_text: TextView = contentView.findViewById(R.id.add_text)
        val tVtitle: TextView = contentView.findViewById(R.id.tVtitle)
        val etEqpWorkID: EditText = contentView.findViewById(R.id.etEqpWorkID)
        when (ress) {
            "server_address" -> {
                add_text.text = "服务器地址："
                etEqpWorkID.setText(Constant.mainUrl)
            }
            "file_address" -> {
                add_text.text = "文件地址："
                etEqpWorkID.setText(Constant.REQUEST_URL_DEBUG)
            }
            "connectTimeout" -> {
                etEqpWorkID.inputType = InputType.TYPE_CLASS_NUMBER
                add_text.text = "网络超时时长："
                val spConnectTimeout = FreeApi_SharePreferencesUtils.getSharePre(
                    "SystemSet",
                    "connectTimeout",
                    applicationContext
                )
                var i: Int
                if (spConnectTimeout.equals("")) {
                    i = Constant.connectTimeout / 1000
                } else {
                    i = spConnectTimeout.toInt() / 1000
                }
                etEqpWorkID.setText(i.toString())
            }
            "mstate" ->{
                add_text.text = "设备编号"
                tVtitle.text = "请输入相关信息"
                add_yes.text = "手动"
                add_no.text = "自动"
            }
        }


        ivClose.setOnClickListener {
            dialog.dismiss()
            finish()
        }
        add_no.setOnClickListener {
            address.onAddress(etEqpWorkID.text.toString(),false)
            if(!"mstate".equals(ress)){
                dialog.dismiss()
                finish()
            }
        }
        add_yes.setOnClickListener {
            address.onAddress(etEqpWorkID.text.toString(),true)
            if(!"mstate".equals(ress)){
                dialog.dismiss()
                finish()
            }

        }

        return dialog
    }

    private fun getTrackOutDialog(type: String, listener: OnSystemSetBot): MaterialDialog {
        val dialog = MaterialDialog(this)
            .cancelable(false)
            .cornerRadius(12f)
            .customView(R.layout.dialog_track_out_start, noVerticalPadding = true)
            .lifecycleOwner(this)
        val contentView = dialog.getCustomView()
        val ivClose: ImageView = contentView.findViewById(R.id.ivClose)
        val set_no: TextView = contentView.findViewById(R.id.set_no)
        val set_yes: TextView = contentView.findViewById(R.id.set_yes)
        val tips_text: TextView = contentView.findViewById(R.id.tips_text)
        val errorText: TextView = contentView.findViewById(R.id.errorText)
        var track = ""
        when (type) {
            "system_set_bot" -> {
                tips_text.setText("是否提交当前设置页面修改数据？")
            }
            "arrival" -> {

                track = intent.getStringExtra("track").toString()
                tips_text.setText(track)
                set_no.visibility = GONE
            }
            "tips" -> {
                track = intent.getStringExtra("tips").toString()
                tips_text.setText(track)
                set_no.visibility = GONE
            }
            "set_number" -> {
                tips_text.setText("是否修改当前正在查询的设备编号？")
            }
            "errorLog" -> {
                val error = intent.getStringExtra("error")
                errorText.text = "错误提示"
                tips_text.text = error
                tips_text.setTextColor(Color.parseColor("#FF0000"))
                set_no.visibility = GONE
            }
        }

//        dialog.onDismiss {
//            Log.e("onActivityResult","onDismiss----------->")
//            if ("track".equals(track)){
//                val intent = Intent()
//                intent.putExtra("again", "again")
//                setResult(2, intent)
//            }
//        }

        ivClose.setOnClickListener {
            if ("arrival".equals(type)){
                val intent = Intent()
                val clazz = Class.forName("com.glory.huaweipda.view.HomeActivity")
                intent.setClass(this, clazz)
                startActivity(intent)
            }
            dialog.dismiss()
            finish()
        }
        set_no.setOnClickListener {
            dialog.dismiss()
            finish()
        }
        set_yes.setOnClickListener {
            val returncode = intent.getStringExtra("returncode")
            if ("set_number".equals(type)) {

            } else {
                if (!returncode.equals("0")){

                }else{
                    val intent = Intent()
                    val clazz = Class.forName("com.glory.huaweipda.view.HomeActivity")
                    intent.setClass(this, clazz)
                    startActivity(intent)
                }

                if ("arrival".equals(type)){
                    val intent = Intent()
                    val clazz = Class.forName("com.glory.huaweipda.view.HomeActivity")
                    intent.setClass(this, clazz)
                    startActivity(intent)
                }

            }
            dialog.dismiss()
            finish()
        }
        return dialog
    }

    private fun getCustomDialog(showList: Boolean, listener: OnConfirmListener): MaterialDialog {

        val dialog = MaterialDialog(this)
            .cancelable(false)
            .cornerRadius(12f)
            .customView(R.layout.dialog_scan_start, noVerticalPadding = true)
            .lifecycleOwner(this)
        val contentView = dialog.getCustomView()
        viewModel.dialog = dialog
        val ivClose: ImageView = contentView.findViewById(R.id.ivClose)
        val etEqpWorkID: EditText = contentView.findViewById(R.id.etEqpWorkID)
        val etUser: EditText = contentView.findViewById(R.id.etUser)
        val etLot: EditText = contentView.findViewById(R.id.etLot)
        val rvLotList: RecyclerView = contentView.findViewById(R.id.rvLotList)
        val ivAddLot: ImageView = contentView.findViewById(R.id.ivAddLot)
        val ivRemoveLot: ImageView = contentView.findViewById(R.id.ivRemoveLot)
        val tvConfirm: TextView = contentView.findViewById(R.id.tvConfirm)
        ivAddLot.visibility = if (showList) View.VISIBLE else View.GONE
        rvLotList.visibility = if (showList) View.VISIBLE else View.GONE
        etLot.visibility = if (showList) View.GONE else View.VISIBLE
        val dialogAdapter = DialogAdapter(null)
        rvLotList.layoutManager = LinearLayoutManager(this)
        rvLotList.adapter = dialogAdapter
        dialogAdapter.addData(DialogLotBean())

        etEqpWorkID.requestFocus()
        etEqpWorkID.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun afterTextChanged(edit: Editable?) {
                val toString = edit.toString()
                if (toString.indexOf("\r") >= 0 || toString.indexOf("\n") >= 0) {
                    etEqpWorkID.setText(toString.replace("\r", "").replace("\n", ""));
                    etUser.requestFocus()
                    etUser.setSelection(etUser.getText().length)
                }
            }
        })
        etUser.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun afterTextChanged(edit: Editable?) {
                val toString = edit.toString()
                if (toString.indexOf("\r") >= 0 || toString.indexOf("\n") >= 0) {
                    etUser.setText(toString.replace("\r", "").replace("\n", ""));
                    rvLotList.requestFocus()
                }
            }

        })

        ivClose.setOnClickListener {
            dialog.dismiss()
            this.finish()
        }

        tvConfirm.setOnClickListener {
            if (etEqpWorkID.text.toString().trim() == "" || etUser.text.toString().trim() == "") {
                Toast.makeText(this, "填写数据未完成", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (showList && getLot(dialogAdapter) == "") {
                Toast.makeText(this, "填写数据未完成", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
//            else if (etLot.text.toString().trim() == "" && !showList) {
//                Toast.makeText(this, "填写数据未完成", Toast.LENGTH_SHORT).show()
//                return@setOnClickListener
//            }

            listener.onConfirm(
                etEqpWorkID.text.toString().trim(),
                etUser.text.toString().trim(),
                if (showList) getLot(dialogAdapter) else etLot.text.toString().trim(),
                dialog
            )
        }

        ivAddLot.setOnClickListener {
            dialogAdapter.addData(DialogLotBean())
        }
        ivRemoveLot.setOnClickListener {
            if (dialogAdapter.data.size == 1) {

            } else {
                dialogAdapter.data.removeAt(dialogAdapter.data.size - 1)
                dialogAdapter.notifyDataSetChanged()
            }
        }
        return dialog
    }

    interface OnConfirmListener {
        fun onConfirm(eqpID: String, user: String, lotID: String,dialog:MaterialDialog)
    }

    interface OnSystemSetBot {
        fun onSystemSetBot(system_set_bot: String)
    }

    interface OnAddressDialog {
        fun onAddress(address: String,isState:Boolean)
    }

    interface OnRegionSelectionDialog {
        fun onRegionSelection(selection: String)
    }

    private fun getLot(dialogAdapter: DialogAdapter): String {
//        if (dialogAdapter.data.isNotEmpty()) {
        val stringBuilder = StringBuilder()
        for (datum in dialogAdapter.data) {
            if (dialogAdapter.data.indexOf(datum) == dialogAdapter.data.size - 1) {
                stringBuilder.append(datum.Lot)
            } else {
                stringBuilder.append(datum.Lot + ",")
            }
        }

        var s = stringBuilder.toString()
        for (i in 0..5){
            if (s[s.length - 1] == ',') {
                s = s.substring(0, s.length - 1)
            }
        }


        return s
//        }
//        return ""
    }

    private fun getDescDialog(address: OnAddressDialog): MaterialDialog {
        val dialog = MaterialDialog(this)
            .cancelable(false)
            .cornerRadius(12f)
            .customView(R.layout.dialog_desc, noVerticalPadding = true)
            .lifecycleOwner(this)
        val contentView = dialog.getCustomView()

        val ivClose: ImageView = contentView.findViewById(R.id.ivClose)
        val add_no: TextView = contentView.findViewById(R.id.add_no)
        val add_yes: TextView = contentView.findViewById(R.id.add_yes)
        val etEqpWorkID: EditText = contentView.findViewById(R.id.etEqpWorkID)
        ivClose.setOnClickListener {
            dialog.dismiss()
            finish()
        }
        add_no.setOnClickListener {
            address.onAddress(etEqpWorkID.text.toString(),false)
            dialog.dismiss()
            finish()
        }
        add_yes.setOnClickListener {
            address.onAddress(etEqpWorkID.text.toString(),true)
            dialog.dismiss()
            finish()
        }

        return dialog
    }

    override fun onPause() {
        super.onPause()
        finish()
        Log.e("onPause", "onPause called.")
    }

    companion object{
        var aActivity:SkipDialogActivity?=null
        fun setActivity(aActivityin:SkipDialogActivity){
            aActivity = aActivityin
        }
        fun getActivity(){
            aActivity?.getData()
        }
    }

    fun getData(){
        finish()
    }

    override fun initData() {
        val instance = MyApp.instance
        instance!!.handler = handler
        setActivity(this)
    }

    override fun initView(savedInstanceState: Bundle?) {
        initView()
    }

    override fun layoutId(): Int {
        return R.layout.free_ui_layout_tab
    }


}